package com.mutual.myCenter.controller;


import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.mutual.app.pojo.AppResult;
import com.mutual.appUserInfo.pojo.AppUserInfo;
import com.mutual.appUserInfo.pojo.AppUserInfoProduct;
import com.mutual.appUserInfo.service.AppUserInfoProductService;
import com.mutual.appUserInfo.service.AppUserInfoService;
import com.mutual.commom.pojo.ReturnResult;
import com.mutual.commom.util.BusnessUtil;
import com.mutual.commom.util.DateUtil;
import com.mutual.commom.util.JSONUtil;
import com.mutual.commom.util.SystemUtil;
import com.mutual.family.pojo.Family;
import com.mutual.family.service.FamilyService;
import com.mutual.invite.pojo.Invite;
import com.mutual.invite.service.InviteService;
import com.mutual.system.areaInfo.pojo.AreaInfo;
import com.mutual.system.areaInfo.service.AreaInfoService;
/**
 * 个人中心服务
 * @author asus
 *
 */
@Controller
@RequestMapping("/myCenter")
public class MyCenterController{

	@Resource
	private AppUserInfoService appUserInfoService;
	
	@Resource
	private AppUserInfoProductService appUserInfoProductService;
	
	@Resource
	private FamilyService familyService;
	
	@Resource
	private InviteService inviteService;
	
	@Resource
	private AreaInfoService areaInfoService;
	
	private static final Logger log = LoggerFactory.getLogger(MyCenterController.class);
	
	/**
	 * 个人信息统计
	 * @param appUserId
	 * @return
	 */
	@GetMapping("/pensonalStatistics")
	@ResponseBody
	public AppResult selectPensonalStatistics(int appUserId){
		AppResult appResult=appUserInfoService.selectPensonalStatistics(appUserId);
		log.info("个人中心统计返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	/**
	 * 个人与家庭电子凭证列表
	 * @param a
	 * @return
	 */
	@GetMapping("/electronicProductList")
	@ResponseBody
	public AppResult electronicProductList(AppUserInfoProduct a){
		AppResult appResult=new AppResult();
		List<AppUserInfoProduct> appUserInfoProductList=appUserInfoProductService.selectAppUserInfoProductList(a);
		DateTime nowTime=DateTime.now();
		for(AppUserInfoProduct app:appUserInfoProductList){
			Period p = new Period(new DateTime(app.getApplyDate().getTime()),nowTime,PeriodType.days());  
			app.setTotalDays(p.getDays());
			app.setObservationPeriodStatus(BusnessUtil.getObservationPeriodStatus(app.getApplyDate()));
		}
		appResult.setData(appUserInfoProductList);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		log.info("个人与家庭电子凭证列表返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	/**
	 * 个人与家庭电子凭证列表
	 * @param a
	 * @return
	 */
	@GetMapping("/detailElectronicProduct")
	@ResponseBody
	public AppResult detailElectronicProduct(int id){
		AppResult appResult=new AppResult();
		AppUserInfoProduct app=appUserInfoProductService.selectByPrimaryKey(id);
		app.setApplyDateString(DateUtil.date2String(app.getApplyDate(), DateUtil.pattern));
		DateTime nowTime=DateTime.now();
		Period p = new Period(new DateTime(app.getApplyDate().getTime()),nowTime,PeriodType.days());  
		app.setTotalDays(p.getDays());
		app.setObservationPeriodStatus(BusnessUtil.getObservationPeriodStatus(app.getApplyDate()));
		appResult.setData(app);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		log.info("个人与家庭电子凭证详情查看：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	/**
	 * 观察期状态
	 * @return
	 */
	
	
	/**
	 * 家庭信息添加
	 * @param family
	 * @return
	 */
	@PostMapping("/addFamily")
	@ResponseBody
	public AppResult addFamily(Family family,@RequestParam Map<String,Object> param){
		AppResult appResult=new AppResult();
		try {
			int count=familyService.selectTotalCount(param);
			if(count>0){
				appResult.setStatus(AppResult.STATUS_FAILED);
				appResult.setMsg("身份证号存在");
				return appResult;
			}
			familyService.insert(family);
			appResult.setMsg(AppResult.MSG_ADD_SUCCESS);
		} catch (Exception e) {
			log.error("家庭信息添加失败：", e);
			appResult.setMsg(AppResult.MSG_ADD_FAILED);
			appResult.setStatus(AppResult.STATUS_FAILED);
		}
		return appResult;
	}
	
	/**
	 * 邀请人列表
	 * @param invite
	 * @return
	 */
	@GetMapping("/selectInviteList")
	@ResponseBody
	public AppResult selectInviteList(Invite invite){
		AppResult appResult=new AppResult();
		List<Invite> invites=inviteService.selectInviteList(invite);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(invites);
		log.info("邀请人列表返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	
	@PostMapping("/regist")
	@ResponseBody
	public AppResult regist(@RequestParam Map<String,Object> param,AppUserInfo appUserInfo){
		AppResult appResult=new AppResult();
		int count=appUserInfoService.selectAppUserInfoCount(param);
		if(count>0){
			appResult.setStatus(AppResult.STATUS_FAILED);
			appResult.setMsg("用户名已存在");
			return appResult;
		}
		appUserInfoService.regist(appUserInfo);
		appResult.setMsg(AppResult.MSG_ADD_SUCCESS);
		appResult.setData(appUserInfo);
		log.info("注册返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	/**
	 * 登录
	 * @param family
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody
	public AppResult login(AppUserInfo appUserInfo){
		AppResult appResult=new AppResult();
		AppUserInfo loginAppUserInfo=appUserInfoService.appUserLogin(appUserInfo);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(loginAppUserInfo);
		log.info("登录返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	/**
	 * 密码重置
	 * @param family
	 * @return
	 */
	@PostMapping("/resetPassword")
	@ResponseBody
	public AppResult resetPassword(AppUserInfo appUserInfo){
		AppResult appResult=new AppResult();
		try {
			appUserInfoService.resetPassword(appUserInfo);
			appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
			appResult.setStatus(AppResult.STATUS_SUCCESS);
		} catch (Exception e) {
			appResult.setMsg("重置失败");
			appResult.setStatus(AppResult.STATUS_FAILED);
		}
		log.info("密码重置返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	/**
	 * 更新个人信息
	 * @param appUserInfo
	 * @return
	 */
	@PostMapping("/updateAppUserInfo")
	@ResponseBody
	public AppResult updateAppUserInfo(AppUserInfo appUserInfo){
		AppResult appResult=new AppResult();
		try {
			if(!StringUtils.isEmpty(appUserInfo.getPassword())){
				appUserInfo.setPassword(DigestUtils.md5DigestAsHex(appUserInfo.getPassword().getBytes()));
			}
			appUserInfoService.updateByPrimaryKey(appUserInfo);
			appResult.setMsg(AppResult.MSG_UPDATE_SUCCESS);
		} catch (Exception e) {
			log.error("个人信息修改失败：", e);
			appResult.setMsg(AppResult.MSG_UPDATE_FAILED);
			appResult.setStatus(AppResult.STATUS_FAILED);
		}
		return appResult;
	}
	
	/**
	 * 登陆人详情
	 * @param invite
	 * @return
	 */
	@GetMapping("/detailAppUser")
	@ResponseBody
	public AppResult detailAppUser(int appUserId){
		AppResult appResult=new AppResult();
		AppUserInfo appUserInfo=appUserInfoService.selectByPrimaryKey(appUserId);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(appUserInfo);
		log.info("个人信息返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	/**
	 * 区域信息展示
	 * @param invite
	 * @return
	 */
	@GetMapping("/selectAreaInfoList")
	@ResponseBody
	public AppResult selectAreaInfoList(AreaInfo info){
		AppResult appResult=new AppResult();
		info.setState(AreaInfo.AreaInfoStateEnum.STATE_YES.getValue());
		List<AreaInfo> areaInfos=areaInfoService.findAreaInfoList(info);
		appResult.setMsg(AppResult.MSG_SELECT_SUCCESS);
		appResult.setData(areaInfos);
		log.info("区域信息返回：{}",JSONUtil.getJSONFromObj(appResult));
		return appResult;
	}
	
	
	/**
	 * 更新地址
	 * @param appUserInfo
	 * @return
	 */
	@PostMapping("/updateAppUserInfoAreaInfo")
	@ResponseBody
	public AppResult updateAppUserInfoAreaInfo(AppUserInfo appUserInfo,@RequestParam Map<String,String> param){
		AppResult appResult=new AppResult();
		try {
			AreaInfo cityAreaInfo=areaInfoService.selectByPrimaryKey(appUserInfo.getAreaCityId());
			AreaInfo provinceAreaInfo=areaInfoService.selectByPrimaryKey(appUserInfo.getAreaProvinceId());
			if(SystemUtil.getInt(appUserInfo.getAreaId())!=0){
				AreaInfo areaInfo=areaInfoService.selectByPrimaryKey(appUserInfo.getAreaId());
				appUserInfo.setAreaCode(areaInfo.getCode());
				appUserInfo.setAreaName(areaInfo.getName());
			}
			appUserInfo.setAreaProvince(provinceAreaInfo.getName());
			appUserInfo.setAreaProvinceCode(provinceAreaInfo.getCode());
			appUserInfo.setAreaCity(cityAreaInfo.getName());
			appUserInfo.setAreaCityCode(cityAreaInfo.getCode());
			appUserInfoService.updateByPrimaryKey(appUserInfo);
			appResult.setMsg(AppResult.MSG_UPDATE_SUCCESS);
			if(!StringUtils.isEmpty(param.get("appInvitationCode"))){
				this.insertInvite(appResult, appUserInfo, param.get("appInvitationCode"));
			}
		} catch (Exception e) {
			log.error("地址修改失败：", e);
			appResult.setMsg(AppResult.MSG_UPDATE_FAILED);
			appResult.setStatus(AppResult.STATUS_FAILED);
		}
		return appResult;
	}
	
	/**
	 * 填写邀请码
	 */
	private void insertInvite(AppResult appResult,AppUserInfo appUserInfo,String appInvitationCode) throws Exception{
		Map<String,Object> param=Maps.newHashMap();
		param.put("invitationCode", appInvitationCode);
		List<AppUserInfo> appUserInfos = appUserInfoService.selectAppUserInfoList(param);
		if(appUserInfos.isEmpty()){
			appResult.setStatus(AppResult.STATUS_FAILED);
			appResult.setMsg("邀请码填写有误");
			return;
		}
		Invite invite=new Invite();
		AppUserInfo selectAppUserInfo=appUserInfos.get(0);
		invite.setAppUserId(selectAppUserInfo.getId());
		invite.setBeAppUserId(appUserInfo.getId());
		invite.setBeAppUserName(appUserInfo.getRealName());
		invite.setInvitationCode(appInvitationCode);
		invite.setCreateDate(new Date());
		inviteService.insert(invite);
		appResult.setMsg(AppResult.MSG_UPDATE_SUCCESS);
	}
}
